import {ref, nextTick, onUnmounted, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {
    ChatDotRound,
    Setting,
    Position,
    Expand,
    Fold,
    DocumentCopy,
    Edit,
    Upload,
    Loading,
    MoreFilled,
    Delete,
    Tools,
    Message,
    SwitchButton,
    ArrowDown,
    User
} from '@element-plus/icons-vue'

import {useRouter} from 'vue-router'
import {getToken, removeToken} from "@/utils/auth";
import { fetchEventSource } from '@microsoft/fetch-event-source';
export function useHome() {
    const isCollapsed = ref(false)
    const circleUrl = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
    const aiAvatar = ref(require('@/assets/images/ai.png'))
    const inputMessage = ref('')
    const isLoading = ref(false)
    const chatContainerRef = ref(null)

    // 聊天历史记录
    const chatHistory = ref([

    ])

    // 聊天消息数据
    const chatMessages = ref([
        {
            role: 'assistant',
            content: '你好！我是 Sage，一个 AI 助手。我可以帮助你回答问题、编写代码、分析数据等。请问有什么我可以帮你的吗？'
        }
    ])

    const toggleSidebar = () => {
        isCollapsed.value = !isCollapsed.value
    }

    function autoResize(event) {
        const textarea = event.target
        textarea.style.height = 'auto'
        textarea.style.height = textarea.scrollHeight + 'px'
    }

    // 滚动到底部
    const scrollToBottom = async () => {
        await nextTick()
        if (chatContainerRef.value) {
            chatContainerRef.value.scrollTop = chatContainerRef.value.scrollHeight
        }
    }

    // 添加一个变量来存储当前的 EventSource
    const currentEventSource = ref(null)

    // 发送消息
    const handleSend = async () => {
        if (!inputMessage.value.trim() || isLoading.value) return

        // 如果存在之前的连接，先关闭
        if (currentEventSource.value) {
            currentEventSource.value.close()
        }

        // 添加用户消息
        chatMessages.value.push({
            role: 'user',
            content: inputMessage.value
        })

        const userMessage = inputMessage.value
        inputMessage.value = ''
        isLoading.value = true

        try {
            // 添加一个空的助手消息用于流式显示
            const assistantMessageIndex = chatMessages.value.length;

            // 确保先添加消息对象后再操作
            chatMessages.value.push({
                role: 'assistant',
                content: ''
            });

            // 创建一个新的控制器并保存引用
            const controller = new AbortController();
            currentEventSource.value = controller;

            await fetchEventSource('/dev-api/chat/conversation', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'text/event-stream',
                    'Authorization': 'Bearer ' + getToken()
                },
                body: JSON.stringify(userMessage),
                signal: controller.signal, // 添加信号

                onmessage(event) {
                    if (event.data === '[DONE]') {
                        isLoading.value = false;
                        controller.abort();
                        currentEventSource.value = null; // 清除引用
                        return;
                    }

                    // 添加安全检查
                    if (chatMessages.value[assistantMessageIndex] &&
                        typeof chatMessages.value[assistantMessageIndex].content === 'string') {
                        // 追加内容
                        chatMessages.value[assistantMessageIndex].content += event.data;
                        scrollToBottom();
                    }
                },

                onclose() {
                    console.log('连接已关闭');
                    currentEventSource.value = null;
                    isLoading.value = false;
                    return false; // 不重新连接
                },

                onerror(error) {
                    console.error('SSE错误:', error);
                    isLoading.value = false;
                    currentEventSource.value = null; // 清除引用

                    // 错误处理...

                    return false; // 不重新连接
                }
            });

        } catch (error) {
            console.error('发送消息失败:', error);
            ElMessage.error('发送消息失败');
            isLoading.value = false;
            currentEventSource.value = null; // 确保清除引用
        }
    }


    // 这些函数需要根据您的UI实现
    function addMessageToChat(sender, content, isPending = false) {
        // 实现添加消息到聊天界面的逻辑
        // 返回消息ID，以便后续更新
    }

    function updateChatMessage(messageId, content) {
        // 实现更新消息内容的逻辑
    }

    function finalizeChatMessage(messageId, content) {
        // 实现完成消息的逻辑，可能包括添加样式或标记
    }

    // 组件卸载时清理连接
    onUnmounted(() => {
        if (currentEventSource.value) {
            currentEventSource.value.close()
        }
    })

    // 复制消息
    const handleCopy = (content) => {
        navigator.clipboard.writeText(content)
        ElMessage({
            message: '复制成功',
            type: 'success',
            plain: true,
        })
    }

    // 开始新对话


    // 处理历史记录操作
    const handleCommand = (command, chat) => {
        switch (command) {
            case 'rename':
                ElMessageBox.prompt('请输入新的对话名称', '重命名', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    inputValue: chat.title,
                    inputPattern: /\S+/,
                    inputErrorMessage: '名称不能为空'
                }).then(({value}) => {
                    const index = chatHistory.value.findIndex(item => item.id === chat.id)
                    if (index !== -1) {
                        chatHistory.value[index].title = value
                    }
                    ElMessage.success('重命名成功')
                }).catch(() => {
                })
                break
            case 'delete':
                ElMessageBox.confirm(
                    '确定要删除这个对话吗？',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    chatHistory.value = chatHistory.value.filter(item => item.id !== chat.id)
                    ElMessage.success('删除成功')
                }).catch(() => {
                })
                break
        }
    }

    //设置按钮
    const router = useRouter();
    const handleSettingCommand = (command) => {
        switch (command) {
            case 'profile':
                // 处理点击个人中心的逻辑
                router.push('/user/profile');
                break;
            case 'settings':
                ElMessage.info('打开系统设置')
                break;
            case 'contact':
                ElMessage.info('打开联系我们')
                break;
            case 'logout':
                ElMessageBox.confirm(
                    '确定要退出登录吗？',
                    '提示',
                    {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    // 这里添加退出登录的具体逻辑
                    removeToken();
                    router.push('/login');
                    ElMessage.success('已退出登录')
                }).catch(() => {
                    ElMessage.info('已取消操作')
                })
                break;
        }
    }

    return {
        // 状态
        isCollapsed,
        aiAvatar,
        inputMessage,
        isLoading,
        chatContainerRef,
        chatHistory,
        chatMessages,

        // 方法
        toggleSidebar,
        autoResize,
        scrollToBottom,
        handleSend,
        handleCopy,
        handleCommand,
        handleSettingCommand
    }
}

// 导出图标组件
export const icons = {
    ChatDotRound,
    Setting,
    Position,
    Expand,
    Fold,
    DocumentCopy,
    Edit,
    Upload,
    Loading,
    MoreFilled,
    Delete,
    Tools,
    Message,
    SwitchButton,
    ArrowDown,
    User
}